﻿@inject IJSRuntime JS
@inject IHttpService _httpService
@implements IDisposable

@code {
    [Parameter]
    public EventCallback<HumanMachineVerificationResult> OnVerficated { get; set; }
    [Parameter]
    public bool WaitChecked { get; set; }

    bool isChecked;

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }


    private DotNetObjectReference<HumanMachineVerification> objRef;

    public async Task StartVerification()
    {
        try
        {
            isChecked = false;

            var geetestCodeModel = await _httpService.GetAsync<GeetestCodeModel>("api/account/GetGeetestCode");

            objRef = DotNetObjectReference.Create(this);
            await JS.InvokeAsync<string>("initGeetestBindCAPTCHA", objRef, geetestCodeModel.Gt, geetestCodeModel.Challenge, geetestCodeModel.Success);

            while(!isChecked&&WaitChecked)
            {
                await Task.Delay(500);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "初始化极验人机验证失败");
            await OnVerficated.InvokeAsync(new HumanMachineVerificationResult());
        }
    }

    [JSInvokable]
    public async Task OnChecked(string challenge, string validate, string seccode)
    {
        await OnVerficated.InvokeAsync(new HumanMachineVerificationResult
        {
            Seccode = seccode,
            Success = true,
            Challenge = challenge,
            Validate = validate
        });

        isChecked = true;

    }

    [JSInvokable]
    public async Task OnCancel()
    {
        await OnVerficated.InvokeAsync(new HumanMachineVerificationResult());
        isChecked = true;
    }

    #region 释放实例
    public void Dispose()
    {
        if (objRef != null)
        {
            objRef?.Dispose();
        }
        isChecked = true;
        GC.SuppressFinalize(this);
    }
    #endregion
}
